package Annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@CustomClassAnnotation(value = "Test")
public class AnotationTest {
    @CustomFieldAnnotation(msg = "Id")
    private int id;

    @CustomFieldAnnotation
    private String name;

    public static void main(String[] args) {
        boolean hasAnnotation = AnotationTest.class.isAnnotationPresent(CustomClassAnnotation.class);
        if (hasAnnotation) {
            CustomClassAnnotation customClassAnnotation = AnotationTest.class
                    .getAnnotation(CustomClassAnnotation.class);
            // 获取类的注解
            System.out.println("value:" + customClassAnnotation.value());
        }
        try {
            Field a = AnotationTest.class.getDeclaredField("a");
            a.setAccessible(true);
            // 获取一个成员变量上的注解
            CustomFieldAnnotation check = a.getAnnotation(CustomFieldAnnotation.class);
            if (check != null) {
                System.out.println("msg value:" + check.msg());
            }
            Method testMethod = AnotationTest.class.getDeclaredMethod("testMethod");
            if (testMethod != null) {
                // 获取方法中的注解
                Annotation[] ans = testMethod.getAnnotations();
                for (int i = 0; i < ans.length; i++) {
                    System.out.println("method testMethod annotation:" + ans[i].annotationType().getSimpleName());
                }
            }
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}
